import cv2
import numpy as np
from datetime import datetime
import configparser



cfp = configparser.ConfigParser()
cfp.read("cv-config.ini")
camid = int(cfp.get("system", "camid"))

cap = cv2.VideoCapture(camid)

cap.set(3, int(cfp.get("camset", "wigth")))
cap.set(4, int(cfp.get("camset", "higth")))
liangdu = int(cfp.get("camset", "liangdu"))
cap.set(cv2.CAP_PROP_BRIGHTNESS, liangdu)
duibidu = int(cfp.get("camset", "duibidu"))
cap.set(cv2.CAP_PROP_CONTRAST, duibidu)
cap.set(cv2.CAP_PROP_SATURATION, int(cfp.get("camset", "baohedu")))
cap.set(cv2.CAP_PROP_HUE, int(cfp.get("camset", "sediao")))
cap.set(cv2.CAP_PROP_EXPOSURE, int(cfp.get("camset", "baoguang")))
fps = int(cfp.get("camset", "fps"))
cap.set(5, fps)
cap.set(cv2.CAP_PROP_FPS, fps)
lownum = int(cfp.get("system", "lownum"))
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
kernel2 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (10, 10))



while True:
    boom = f = open('./life.txt', 'w+')
    boom.write("V3.1.2-20230505")
    boom.close()
    flag, frame = cap.read()
    if not flag:
        break

    frame = cv2.flip(frame, 1)
    time_cur = datetime.now().strftime('1%H%M%S%f')

    gray = cv2.cvtColor(frame, code=cv2.COLOR_BGR2GRAY)

    ret, dst = cv2.threshold(gray, lownum, 255, cv2.THRESH_BINARY)

    dst = cv2.morphologyEx(dst, cv2.MORPH_OPEN, kernel)

    dst = cv2.morphologyEx(dst, cv2.MORPH_CLOSE, kernel2)
    dst = cv2.morphologyEx(dst, cv2.MORPH_ERODE, kernel2)
    contours, hierarchy = cv2.findContours(dst, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    if (len(contours) > 0):
        Arr = []
        for c in range(len(contours)):
            Arr.append(cv2.contourArea(contours[c]))
        max_id = Arr.index(max(Arr))
        try:

            coord = contours[max_id][1]
            point = (coord[0][0], coord[0][1])
            str1 = str(time_cur)
            sqltxt = str(coord[0][0]) + "|" + str(coord[0][1])
            f = open('./data.txt', 'w+')
            f2 = open('./time.txt', 'w+')
            f2.write(str1)
            f.write(sqltxt)
            f.close()
            f2.close()
        except :
            print("Error")
cap.release()
